<template>
  <!-- textarea弹性容器 -->
  <div class="elasticity-textarea">
    <textarea 
      class="base-textarea base-nav-scrollbar"
      :class="props.className" 
      :placeholder="props.placeholder" 
      v-model="textareaValue"
      :maxLength="maxLength"
      :rows="textareaRows"
      @keydown="checkEnter(event)"
      @input="textareaInput"
    />
  </div>
</template>
<script setup>
import {
  defineProps,
  defineEmits,
  ref,
  watch
} from "vue";

const props = defineProps({
  value: {
    type: String,
    default: "",
  },
  placeholder: {
    type: String,
    default: "Type a message...",
  },
  className: {
    type: String,
    default: "",
  },
  maxLength: {
    type: Number,
    default: 180
  }
});
const $emit = defineEmits(["update:value"]);
const textareaValue = ref("");
const textareaRows = ref(1);

watch(() => props.value, val => {
  if (!val) {
    textareaValue.value = "";
    textareaRows.value = 1;
  }
});

const textareaInput = () => {
  $emit("update:value", textareaValue.value);
  rowChange();
};

// 更新行数据
const rowChange = () => {
  let row = 0;
  textareaValue.value.split("\n").forEach((item) => {
    if (item.length === 0) {
      row += 1;
    } else {
      row += Math.ceil(item.replace(/[\u0391-\uFFE5]/g, "aa").length / 40);
    }
  });
  // console.log("rowChange ==> ", row);
  textareaRows.value = row <= 4 ? row : 4;
};

// 禁止直接回车换行
const checkEnter = (e) => {
  let et = e || window.event;
  let keycode = et.charCode || et.keyCode;
  if (keycode == 13) {
    if (window.event) {
      console.log("window ==> ", window);
      window.event.returnValue = false;
    } else {
      e.preventDefault(); //for firefox
    }
  }
};

</script>
<style lang="scss" scoped>
.elasticity-textarea {
  width: 100%;
  .base-textarea {
    width: 100%;
    margin: 0 12px;
    flex: 1;
    outline: none;
    resize: none;
    -webkit-user-select: auto;
    background: none;
    border: none;
    color: rgba(255, 255, 255, 0.80);
    font-size: 14px;
    font-weight: 500;
    font-family: Arial, Helvetica, sans-serif !important;
    line-height: 20px;
    max-height: 80px;
  }
}
</style>